package controller;

import model.User;
import model.UserDao;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.awt.image.RenderedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Base64;

@MultipartConfig
@WebServlet("/update")
public class UpdateServlet extends HttpServlet {
    //这是资料更新，前端给后端发送post请求，后端读取文件。
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String nickname=req.getParameter("nickname");
        String password=req.getParameter("password");
        HttpSession session=req.getSession(false);
        User user= (User) session.getAttribute("user");
        Part part=req.getPart("picture");
        if (session==null){
            resp.setStatus(403);
        }
        if (user==null){
            resp.setStatus(403);
        }
        byte[] bytes=new byte[99999];
        part.getInputStream().read(bytes);
        String base64=Base64.getEncoder().encodeToString(bytes);
        System.out.println("data:image/"+ "png" +";base64,"+base64);
        base64 = base64.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n
        UserDao userDao=new UserDao();
        userDao.update(user.getUserId(),password,nickname, base64);
    }
}
